package com.sanpu.kxe.business.main.view;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.view.View;
import android.widget.Toast;

import com.sanpu.kxe.R;
import com.sanpu.kxe.base.BaseTitleActivity;
import com.sanpu.kxe.business.main.bean.CertificationOutput;
import com.sanpu.kxe.business.main.contract.LinkfaceLivenessContract;
import com.sanpu.kxe.business.main.contract.MainConfig;
import com.sanpu.kxe.business.main.presenter.LinkfaceLivenessPresenter;
import com.sanpu.kxe.common.interfaces.CommonConfig;
import com.sanpu.kxe.jump.linkface.Constants;

import butterknife.OnClick;

/**
 * Description：活体检测
 * Created by 薛勇军 on 2019/5/22.
 */

public class LinkfaceLivenessActivity extends BaseTitleActivity implements LinkfaceLivenessContract.View {

    private LinkfaceLivenessContract.Presenter mPresenter;

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_linkface_liveness;
    }

    @Override
    protected void initView() {
        super.initView();
        commonTitle.setTitle("实名认证");
        CertificationOutput certificationOutput =
                (CertificationOutput) getIntent().getSerializableExtra(MainConfig.INTENT_CERTIFICATION_INPUT);
        mPresenter = new LinkfaceLivenessPresenter(this, certificationOutput);
        reaquestPersmision();
    }

    @OnClick({R.id.next})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.next:
                onClickStartDetectLiveness();
                break;
        }
    }

    /**
     * 开始检测
     */
    private void onClickStartDetectLiveness() {
        if (isMarshmallow()) {
            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                // Permission has not been granted and must be
                // requested.
                if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
                    // Provide an additional rationale to the user if
                    // the permission was not granted
                    // and the user would benefit from additional
                    // context for the use of the permission.
                }
                // Request the permission. The result will be received
                // in onRequestPermissionResult()
                requestPermissions(
                        new String[]{Manifest.permission.CAMERA}, CommonConfig.PERMISSION_REQUEST_CAMERA);
            } else {
                // Permission is already available, start camera preview
                requestWriteSdPermission();
            }
        } else {
            requestWriteSdPermission();
        }
    }

    private void requestWriteSdPermission() {
        if (isMarshmallow()) {

            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                // Permission has not been granted and must be
                // requested.

                if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    // Provide an additional rationale to the user if
                    // the permission was not granted
                    // and the user would benefit from additional
                    // context for the use of the permission.
                }
                // Request the permission. The result will be received
                // in onRequestPermissionResult()
                requestPermissions(
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        CommonConfig.PERMISSION_REQUEST_SD_WRITE);
            } else {
                // Permission is already available, start camera preview
                mPresenter.startLiveness();
            }
        } else {
            mPresenter.startLiveness();
        }
    }

    /**
     * 校验活体检测权限
     */
    private void reaquestPersmision() {
        if (isMarshmallow()) {
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    // Provide an additional rationale to the user if
                    // the permission was not granted
                    // and the user would benefit from additional
                    // context for the use of the permission.
                }
                // Request the permission. The result will be received
                // in onRequestPermissionResult()
                requestPermissions(
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, CommonConfig.PERMISSION_REQUEST_WRITE);
            } else {
                // Permission is already available, start camera preview
                mPresenter.initSDK();
            }
        } else {
            mPresenter.initSDK();
        }
    }

    private static boolean isMarshmallow() {
        return Build.VERSION.SDK_INT >= 23;
    }

    /**
     * 回调
     */
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] grantResults) {
        if (requestCode == CommonConfig.PERMISSION_REQUEST_CAMERA) {
            // Request for camera permission.
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission has been granted. Start camera preview Activity.
                requestWriteSdPermission();
            } else {
                // Permission request was denied.
                Toast.makeText(this, Constants.ERROR_CAMERA_REFUSE,
                        Toast.LENGTH_SHORT).show();
            }
        }
        if (requestCode == CommonConfig.PERMISSION_REQUEST_SD_WRITE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission has been granted. Start camera preview Activity.
                mPresenter.startLiveness();
            } else {
                // Permission request was denied.
                Toast.makeText(this, Constants.ERROR_SD_REFUSE,
                        Toast.LENGTH_SHORT).show();
            }
        }

        if (requestCode == CommonConfig.PERMISSION_REQUEST_WRITE) {
            // Request for camera permission.
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission has been granted. Start camera preview Activity.
                mPresenter.initSDK();
            } else {
                // Permission request was denied.
                Toast.makeText(this, Constants.ERROR_STORAGE_REFUSE,
                        Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onActivityResult(final int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CommonConfig.KEY_TO_DETECT_REQUEST_CODE) {
            mPresenter.dealDetectResult(resultCode);
        }
    }

    @Override
    protected boolean hasBindEventBus() {
        return false;
    }

    @Override
    public void setPresenter(LinkfaceLivenessContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.onDestroyPresenter();
            mPresenter = null;
        }
    }
}
